import React, { useEffect, useState } from "react"
import { useLocation } from "react-router-dom"
import NavTop from "../../components/NavTop"
import { http } from "../../utils/http"
import ArticlesItem from "../../components/ArticlesItem"
import { InfiniteScroll, DotLoading } from "antd-mobile"
const InfiniteScrollContent = ({ hasMore }) => {
  return (
    <>
      {hasMore ? (
        <>
          <span>Loading</span>
          <DotLoading />
        </>
      ) : (
        <span> 没有更多了 </span>
      )}
    </>
  )
}

function searchResult() {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const location = useLocation()
  const key = location.state
  // 接收搜索结果列表
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [searchList, setSearchList] = useState([])
  // 是否还有数据
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [hasMore, setHasMore] = useState(true)
  // 第几页
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [page, setPage] = useState(1)
  const getData = async (page = 1) => {
    const { data } = await http.get("/search", {
      params: {
        page,
        q: key
      }
    })
    setSearchList(data.data.results)
    return data.data
  }
  // 加载更多
  async function loadMore() {
    setPage(page + 1)
    const res = await getData(page)
    console.log(res)
    setSearchList([...searchList, ...res.results])
    setHasMore(res.page * res.per_page <= res.total_count)
  }
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getData()
    // eslint-disable-next-line
  }, [key])
  return (
    <div>
      <NavTop title="搜索结果"></NavTop>
      <div style={{ paddingTop: "46px" }}>
        {searchList.length > 0 &&
          searchList.map((item) => {
            return (
              <>
                <ArticlesItem key={item.art_id} articles={item}></ArticlesItem>
              </>
            )
          })}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold="400">
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </div>
    </div>
  )
}

export default searchResult
